package com.example.mediaplayer

import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.media.MediaPlayer
import android.content.res.AssetFileDescriptor

import android.content.IntentFilter

import android.content.res.AssetManager
import android.media.MediaPlayer.OnCompletionListener
import android.os.Bundle
import android.util.Log
import android.widget.SeekBar
import java.io.IOException
import java.util.*
import android.os.Message;


class MusicService : Service() {
    var serviceRecevier: MyReceiver? = null
    var assetManager: AssetManager? = null
    var musics = arrayOf("music1.mp3", "music2.mp3", "music3.mp3","music4.mp3")
    var mediaPlayer: MediaPlayer? = null
    var status = 0x11
    var current = 0
    private val CTL_ACTION = "org.xr.action.CTL_ACTION"
    val UPDATE_ACTION = "org.xr.action.UPDATE_ACTION"

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()

        assetManager = assets//指定该BroadcastReceiver
        serviceRecevier = MyReceiver()//创建BroadcastReceiver
        val filter = IntentFilter()
        filter.addAction(CTL_ACTION)
        registerReceiver(serviceRecevier, filter)
        mediaPlayer = MediaPlayer()
        mediaPlayer!!.setOnCompletionListener { //current = (current+1)%musics.length;
            current++
            if (current > 3) {
                current = 0
            }
            //发送广播通知Activity更改文本框，进度条改变
            val sendIntent = Intent(UPDATE_ACTION)
            sendIntent.putExtra("current", current)
//            val p: Int = mediaPlayer!!.getCurrentPosition()
//            sendIntent.putExtra("seekbar",p)
            //发送广播，将被Activity组件中的BroadcastReceiver接收到
            sendBroadcast(sendIntent)
            prepareAndPlay(musics[current])
        }
    }

    inner class MyReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val control = intent.getIntExtra("control", -1)
            when (control) {
                1 -> if (status == 0x11) {
                    prepareAndPlay(musics[current])
                    status = 0x12
                } else if (status == 0x12) {
                    mediaPlayer!!.pause()
                    status = 0x13
                } else if (status == 0x13) {
                    mediaPlayer!!.start()
                    status = 0x12
                }
                //stop
                2 -> if (status == 0x12 || status == 0x13) {
                    mediaPlayer!!.stop()
                    status = 0x11
                }
                //last
                3 -> if (current <= 0) {
                    mediaPlayer!!.stop()
                    current = musics.size - 1
                    prepareAndPlay(musics[current])
                    status = 0x12
                } else {
                    mediaPlayer!!.stop()
                    current--
                    prepareAndPlay(musics[current])
                    status = 0x12
                }
                //下一首
                4 -> if (current >= 3) {
                    mediaPlayer!!.stop()
                    current = 0
                    prepareAndPlay(musics[current])
                    status = 0x12
                } else {
                    mediaPlayer!!.stop()
                    current++
                    prepareAndPlay(musics[current])
                    status = 0x12
                }
            }
            //通知Activity更改图标、文本框
            val sendIntent = Intent(UPDATE_ACTION)
            sendIntent.putExtra("update", status)
            sendIntent.putExtra("current", current)
            Log.i("Main","fghjkhjbn  $current")
            sendBroadcast(sendIntent)
        }
    }

    private fun prepareAndPlay(music: String) {
        try {
            val afd = assetManager?.openFd(music)
            mediaPlayer?.reset()
            if (afd != null) {
                mediaPlayer?.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
            }
            mediaPlayer?.prepare()
            mediaPlayer?.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    private fun updateSeekBar() {
        var duration = mediaPlayer?.getDuration();
        var timer = Timer();
        var task = PositionTask();
        timer.schedule(task,100,1000);
    }
    inner class PositionTask:TimerTask(){

       override fun run() {
            // 实时获取数据
            var currentPosition:Int = mediaPlayer!!.getCurrentPosition();
            // handler子线程向UI线程传输数据
            var msg:Message = MainActivity.handler.obtainMessage();
            msg.what = 233;
            // 数据
            var bundle:Bundle =Bundle()
            bundle.putInt("duration",duration);
            bundle.putInt("currentPosition",currentPosition);
            msg.setData(bundle);

            MainActivity.handler.sendMessage(msg);
        }
    }
    // TODO 拖动SeekBar
    fun dragSeekBar(seekBarProgress:Int){
        mediaPlayer?.seekTo(seekBarProgress);
    }
    // TODO 歌曲播放完成的监听
    fun  musicComplete(){
        var mp=MediaPlayer()
        mediaPlayer?.setOnCompletionListener(mp.OnCompletionListener() {
           fun onCompletion( mp:MediaPlayer) {
               mediaPlayer?.seekTo(0);
               mediaPlayer?.start();
            }
        });
    }
}
}